import { deepClone } from '@/utils/tool'
import * as type from './actionTypes'

//reducer其实也是个方法而已,参数是state和action,返回值是新的state
const initState = {
    collapsed: false,
    menu:[],
    leftMenu:null
}

//获取菜单数据
const getMenu = (state, action) => {
    const { payload } = action;
    //菜单数据
    let menu = payload;
    let _menu = deepClone(menu);
    // 左侧菜单对象
    let _leftMenu = {};
    for(let i in _menu){
        let _menuObj = {};
        let _key = parseInt(_menu[i].key);
        delete _menu[i].key;
        _menuObj[_key] = _menu[i];
        Object.assign(_leftMenu, _menuObj)
    }

    return Object.assign({}, state, { menu: menu, leftMenu: _leftMenu})

}

const reducerFun = (state = initState, action) => {
    switch (action.type) {
      case type.MENU_COLLAPSED: 
        return Object.assign({}, state, action.obj)
      case type.GET_MENU_DATA: 
        return getMenu(state, action)
      default:
        return state
    }
}

export default reducerFun;